<template>
  <view>
    <view class="w100 pl-30 pr-30">
      <view class="rows rowsm m-all-20 w100" style="justify-content: space-between;">
        <view class="rows rowsm" style="width: 70%">
          <view style="max-width: 40%;">
            <view class="fs-28 fw-b col000 mr-16 overFlow" v-if="classItem">{{ classItem }}</view>
            <view class="fs-28 col000 mr-16" :class="{ 'fw-b': !classItem }" v-else
              @click="classItem = null, handelType()">
              全部
            </view>
          </view>
          <view class="rows rowsm" @click="showPicker" style="white-space: nowrap;">
            <view class="fs-26 col666 mr-4">切换班级</view>
            <image src="/static/icon_1jt.png" class="w-20 h-20" mode=""></image>
          </view>
          <view class="rows rowsm" @click="classItem = null, handelReset()" style="white-space: nowrap;">
            <view class="fs-26 col666 mr-4">重置</view>
          </view>
        </view>
      </view>
      <!-- 搜索部分 -->
      <view class="w100 bgff mt-10 mb-10 pl-20 pr-20 pt-10 pb-10 br-20">
        <!-- 实践课程 -->
        <view class="rowsb rowsm mb-10 mt-10">
          <!-- <view class="title" style="width:20%;">实践课程：</view> -->
          <!-- <scroll-view scroll-x="true" style="white-space: nowrap;"> -->
          <view class="rows rowsm h100" style="flex-wrap: wrap;">
            <view class="pl-20 pr-20 h-52 rowsc rowsm br-26 fs-26 mr-20 mt-10 mb-10" v-for="(item, index) in practiceType"
              :key="index"
              :style="active == practiceType[index].value ? 'color: #fff;background: linear-gradient(to bottom,#4897FF,#4878FF);' : 'background-color: #F4F4F4;color: #666;'"
              @click="handelPracticeType(index)">{{ item.name }}</view>
          </view>
          <!-- </scroll-view> -->
        </view>
        <view class="rowsb rowsm mb-20 mt-10">
          <scroll-view scroll-x="true" style="white-space: nowrap;">
            <view class="rows rowsm h100">
              <view class="pl-20 pr-20 h-52 rowsc rowsm br-26 fs-26 mr-20" v-for="(item, index) in completionStatus"
                :key="index"
                :style="active2 == item.value ? 'color: #fff;background: linear-gradient(to bottom,#4897FF,#4878FF);' : 'background-color: #F4F4F4;color: #666;'"
                @click="getActive(item.value)">{{ item.name }}</view>
            </view>
          </scroll-view>
        </view>
        <view class="w100 bgff pr-24">
          <view class="rowsb rowsm mb-20 mt-20">
            <view class="title" style="width:20%;">实践任务：</view>
            <uni-data-select v-model="practiceTaskId" :localdata="selectorList"></uni-data-select>
          </view>
          <view class="rows rowsm mb-20">
            <view class="title" style="width:20%;">提交时间：</view>
            <uni-datetime-picker v-model="range" type="daterange" @change="changeTime" />
          </view>
          <ba-tree-picker ref="treePicker" :multiple='true' @select-change="selectChange" title="选择" :localdata="listData"
            valueKey="id" textKey="name" childrenKey="childList" />
        </view>
      </view>

      <view class="title-warp p-all-20 br-20 w100"
        v-if="permissions.find(v => v == '*:*:*') || permissions.find(v => v == 'practice:user:collegeCheck')">
        <checkbox-group @change="allSelectBtn">
          <checkbox :checked="allSelected" value="全选" class="checkbox">全选</checkbox>
        </checkbox-group>

        <button type="primary" :disabled="selectedIds.length == 0" @click="batchMdera(2)">批量通过</button>
        <button :disabled="selectedIds.length == 0" @click="batchMdera(4)">批量驳回</button>
      </view>
      <view class="content-warp mt-20">
        <checkbox-group @change="selectBtn">
          <view class="item-warp" v-for="item in itemList" :key="item.id">
            <view class="txt-warp">
              <text class="title">
                <checkbox :value="String(item.id)" :checked="selectedIds.includes(item.id)"
                  :disabled="item.status != 1 ? true : false" class="checkbox">
                  <uni-tooltip :content="item.projectName" placement="top" v-if="item.projectName.length > 15">
                    {{ item.projectName.slice(0, 15) + '...' }}
                  </uni-tooltip>
                  <text v-else> {{ item.projectName }}</text>
                </checkbox>
              </text>
              <view class="btn" @click.stop="goPage(item)">
                <view v-if="item.status != 3">{{ item.status == 1 ? '未审批' : item.status == 2 ? '审核通过' : '已驳回' }}</view>
                <view v-else>{{ item.acquisitionPoints }}分</view>
              </view>
            </view>

            <view class="rows rowsm rowsb mb-20 mt-20" @click.stop="goPage(item)">
              <view class="ellipsis-text">
                <text class="fw-600 fs-26"> 任务名称：</text>
                <text>{{ item.taskName }}</text>
              </view>
            </view>
            <view class="rows rowsm rowsb mb-20 mt-20" @click.stop="goPage(item)">
              <view>
                <text class="fw-600 fs-26"> 提交时间：</text>
                <text>{{ item.createTime.slice(0, 16) }}</text>
              </view>
              <view>
                <text class="fw-600 fs-26"> 积分上限：</text>
                <text>{{ item.pointsCap }}</text>
              </view>
            </view>
            <view class="rows rowsm rowsb mb-20 mt-20" @click.stop="goPage(item)">
              <view class="rows rowsm">
                <image src="/static/icon_tx.png" class="w-60 h-60 one" mode=""></image>
                <text class="ml-20">{{ item.studentName }} ({{ item.stNumber }})</text>
              </view>
              <view>
                <text class="fw-600 fs-26"> 实践课程：</text>
                <text>
                  <!-- {{ item.taskType == 1 ? '劳动教育' : item.taskType == 2 ? '职业素养' : item.taskType == 3 ? '应急安全'
                    : item.taskType == 4 ? '思政实践' : '创新创业' }} -->
                  {{ (practiceType.find(v => v.value == item.taskType) || {}).name }}
                </text>
              </view>
            </view>
          </view>

        </checkbox-group>
        <view v-if="itemList.length == 0" class="notYet">
          暂无数据
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { Base64 } from 'js-base64';
import baTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue"
export default {
  data() {
    return {
      active: 0,
      active2: 0,
      title: '',
      range: [],
      practiceType: [
        { name: '全部', value: 0 },
      ],
      completionStatus: [
        { name: '全部', value: 0 },
        { name: '未审核', value: 1 },
        { name: '审核通过', value: 2 },
        { name: '已驳回', value: 4 },
      ],
      character: '',
      characterList: [],
      itemList: [],
      total: 0,
      limit: {
        pageNum: 1,
        pageSize: 10,
      },
      proxyIndex: null,
      proxyList: [],
      prozyAddList: [],
      prozyAddIndex: null,
      probjAddList: [],
      probjAddIndex: null,
      pronjAddList: [],
      selectorList: [],
      faceXy: '',
      faceZy: '',
      faceBj: '',
      faceNj: '',
      practiceTaskId: null,
      permissList: [],
      allSelected: null,
      selectedIds: [],
      classItem: null,
      listData: [],
      xyIdList: [],
      zyIdList: [],
      bjIdList: [],
      options: ['选项1', '选项2', '选项3', '选项4'], // 所有选项
      filteredOptions: [], // 过滤后的选项
      selectedOption: '', // 当前选中的选项
      searchText: '', // 搜索文本
      permissions: [],
    };
  },
  components: {
    baTreePicker
  },
  onShow() {
    this.itemList = [];
    this.limit.pageNum = 1;
    this.getList();
  },
  onLoad(e) {
    if (uni.getStorageSync('flag') == 'teacher') {
      this.$tools.axiosFromToken('POST', 'sysUser/getById', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        let getAllInfo = { ...res.data, user: JSON.parse(Base64.decode(res.data.user)) }
        uni.setStorageSync('getInfo', getAllInfo);
        this.permissions = res.data.permissions.flat() || [];
      })
    }
    this.filteredOptions = this.options;
    this.getAllBj();
    this.getSelectorListTaks();
    this.getTypeCongfigList();
    // this.getListProxy();
    // this.getListProzy();
    // this.getListProbj();
    // this.getListPronj();

    // this.permissList = uni.getStorageSync('getInfo').practiceTypes;
    // const typeMap = {
    //   1: { name: '劳动教育', value: 1 },
    //   2: { name: '职业素养', value: 2 },
    //   3: { name: '应急安全', value: 3 },
    //   4: { name: '思政实践', value: 4 },
    //   5: { name: '创新创业', value: 5 }
    // };

    // this.permissList.forEach(v => {
    //   if (typeMap[v]) {
    //     this.practiceType.push(typeMap[v]);
    //   }
    // });
  },
  // 下拉到底部后加载新数据
  onReachBottom() {
    if (this.itemList.length < this.total) {
      this.limit.pageNum++;
      this.getList();
    }
  },
  watch: {
    practiceTaskId(newId) {
      this.limit.pageNum = 1;
      this.getList();
    },
  },
  methods: {
    getTypeCongfigList() {
      this.$tools.axiosFromToken('GET', 'project/practice/type/config/list?pageNum=1&pageSize=50', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.practiceType = [
          { name: '全部', value: 0 }
        ];
        res.rows.forEach(item => {
          this.practiceType.push({ name: item.name, value: item.id })
        })
      })
    },
    handleChange(e) {
      this.selectedOption = this.filteredOptions[e.detail.value];
    },
    handleSearch() {
      if (this.searchText) {
        this.filteredOptions = this.options.filter(option =>
          option.toLowerCase().includes(this.searchText.toLowerCase())
        );
      } else {
        this.filteredOptions = this.options;
      }
    },
    getAllBj() {
      this.$tools.axiosFromToken('POST', 'prouser/getBj', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.listData = [];
        this.listData = res.data;
      })
    },
    // 显示选择器
    showPicker() {
      this.$nextTick(() => {
        this.$refs.treePicker._show();
      })
    },
    //监听选择（ids为数组）
    selectChange(ids, names) {
      this.classItem = names;
      this.xyIdList = [];
      this.zyIdList = [];
      this.bjIdList = [];
      ids.forEach(v => {
        if (v.type == 'xy') {
          this.xyIdList.push(v.id)
        }
        if (v.type == 'zy') {
          this.zyIdList.push(v.id)
        }
        if (v.type == 'bj') {
          this.bjIdList.push(v.id)
        }
      })
      this.handelType();
    },
    getSelectorListTaks() {
      this.selectorList = [];
      this.$tools.axiosFromToken('GET', 'project/task/selectorForList?taskNameSort=desc', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        res.rows.forEach(item => {
          this.selectorList.push({ text: item.taskName, value: item.id })
        })
      })
    },
    getActive(item) {
      this.limit.pageNum = 1;
      this.active2 = item;
      this.getList();
    },
    selectBtn(e) {
      this.selectedIds = [];
      if (e.detail.value.length > 20) {
        e.detail.value.slice(0, 20).forEach(v => {
          this.selectedIds.push(Number(v))
        })
        this.$tools.showtt('最多只能批量操作20条数据');
      } else {
        e.detail.value.forEach(v => {
          this.selectedIds.push(Number(v))
        })
      }
      this.allSelected = this.itemList
        .filter(v => v.status == 1).length == this.selectedIds.length && this.selectedIds.length <= 20 ? '全选' : false;
      this.$forceUpdate();
    },
    allSelectBtn(e) {
      if (e.detail.value[0] == '全选') {
        this.selectedIds = this.itemList
          .filter(v => v.status == 1)
          .map(v => v.id);

        if (this.selectedIds.length > 20) {
          this.selectedIds = this.selectedIds.slice(0, 20);
          this.$tools.showtt('最多只能批量操作20条数据');
        }
      } else {
        this.selectedIds = [];
      }
    },
    changeProxy(e) {
      this.proxyIndex = e.detail.value;
      this.faceXy = this.proxyList[e.detail.value].id;
    },
    changeProzy(e) {
      this.prozyAddIndex = e.detail.value;
      this.faceZy = this.prozyAddList[e.detail.value].id;
    },
    changeProbj(e) {
      this.probjAddIndex = e.detail.value;
      this.faceBj = this.probjAddList[e.detail.value].id;
    },
    changeTime(e) {
      this.limit.pageNum = 1;
      this.range = e;
      this.getList();
    },
    handelType() {
      this.limit.pageNum = 1;
      this.getList();
    },
    // 查询学院
    getListProxy() {
      this.$tools.axiosFromToken('GET', 'project/proxy/listTotal', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        // this.proxyList = res.rows
        res.rows.forEach(item => {
          this.proxyList.push({ text: item.name, value: item.id })
        })
      })
    },
    // 查询专业
    getListProzy() {
      this.$tools.axiosFromToken('GET', 'project/prozy/listTotal', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        // this.prozyAddList = res.rows
        res.rows.forEach(item => {
          this.prozyAddList.push({ text: item.name, value: item.id })
        })
      })
    },
    // 查询班级
    getListProbj() {
      this.$tools.axiosFromToken('GET', 'project/probj/listTotal', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        // this.probjAddList = res.rows
        res.rows.forEach(item => {
          this.probjAddList.push({ text: item.name, value: item.id })
        })
      })
    },
    // 查询年级
    getListPronj() {
      this.$tools.axiosFromToken('GET', 'project/class/selectorForList', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        // this.probjAddList = res.rows
        res.rows.forEach(item => {
          this.pronjAddList.push({ text: item.name, value: item.name })
        })
      })
    },
    getList() {
      const data = {
        xyIdList: this.xyIdList,
        zyIdList: this.zyIdList,
        bjIdList: this.bjIdList,
        isH5: 1,
        practiceTaskId: this.practiceTaskId,
        taskType: this.active === 0 ? null : this.active,
        status: this.active2 === 0 ? null : this.active2,
        startTime: this.range.length > 0 ? this.range[0] + " 00:00:00" : null,
        endTime: this.range.length > 0 ? this.range[1] + " 23:59:59" : null,
      };
      this.$tools.axiosFromToken('GET', `practice/user/getCollegeCheck?pageNum=${this.limit.pageNum}&pageSize=${this.limit.pageSize}`, data, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.total = res.total
        if (this.limit.pageNum == 1) {
          this.itemList = res.rows;
        } else {
          this.itemList = [...this.itemList, ...res.rows];
        }
      })
    },
    batchMdera(status) {
      const data = {
        ids: this.selectedIds,
        status
      }
      uni.showModal({
        title: `确认批量${status == 2 ? '审核' : '驳回'}`,
        content: `是否确认批量${status == 2 ? '审核' : '驳回'}${this.selectedIds.length}条任务数据项？`,
        success: (res) => {
          if (res.confirm) {
            if (status != 2) {
              // 弹出输入框让用户填写驳回理由
              uni.showModal({
                title: '驳回原因',
                content: '',
                editable: true,
                placeholderText: '请填写驳回原因',
                success: (promptRes) => {
                  if (promptRes.confirm) {
                    // 用户确认了输入框的内容
                    const reason = promptRes.content;  // 获取用户输入的驳回理由

                    if (reason.trim() === '') {
                      // 如果输入为空，提醒用户填写驳回理由
                      uni.showToast({
                        title: '驳回理由不能为空',
                        icon: 'none',
                      });
                      return;
                    }

                    data.collegeCheckTime = this.getDate();
                    data.reason = reason;
                    this.$tools.axiosFromToken('POST', 'practice/user/check', JSON.stringify(data), '加载中').then(res => {
                      this.$tools.showtt(res.msg)
                      if (res.code != 200) return
                      this.selectedIds = [];
                      this.itemList = [];
                      this.allSelected = false;
                      this.getList();
                    })
                  }
                }
              })
            } else {
              this.$tools.axiosFromToken('POST', 'practice/user/check', JSON.stringify(data), '加载中').then(res => {
                this.$tools.showtt(res.msg)
                if (res.code != 200) return
                this.selectedIds = [];
                this.itemList = [];
                this.allSelected = false;
                this.getList();
              })
            }
          } else if (res.cancel) {
            // 用户点击了“取消”
            console.log('取消删除');
          }
        }
      });
    },
    getDate() {
      const now = new Date();

      const year = now.getFullYear();  // 获取年份
      const month = String(now.getMonth() + 1).padStart(2, '0');  // 获取月份，月从 0 开始，所以需要加 1，使用 padStart 补充零
      const day = String(now.getDate()).padStart(2, '0');  // 获取日期，使用 padStart 补充零

      const hours = String(now.getHours()).padStart(2, '0');  // 获取小时，补充零
      const minutes = String(now.getMinutes()).padStart(2, '0');  // 获取分钟，补充零
      const seconds = String(now.getSeconds()).padStart(2, '0');  // 获取秒数，补充零

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handelPracticeType(index) {
      this.active = this.practiceType[index].value
      this.getList()
    },
    goPage(item) {
      // if (item.status == '进行中' || item.status == '已结束' || item.status == '未发布') {
      this.$tools.goNext(`/teacher/practiceTask/practiceDetail?title=${this.title}&id=${item.id}&typeAudit=2&auditState=${item.status}`)
      // }
    },
    addTask() {
      this.$tools.goNext(`/teacher/practiceTask/addPractice`)
    },
    handelReset() {
      this.limit.pageNum = 1;
      this.range = [];
      this.active = 0;
      this.active2 = 0;
      this.xyIdList = null;
      this.zyIdList = null;
      this.bjIdList = null;
      this.practiceTaskId = null;
      this.getAllBj();
      this.getList();
    },
  }
}
</script>

<style lang="scss">
page {
  background-color: #f4f5f7;
  padding-bottom: 10px;

  ::v-deep .uni-select__input-box {
    min-height: 32px !important;
  }

  ::v-deep .uni-date__x-input {
    height: auto !important;
    padding: 5px !important;
  }
}

::v-deep .uni-flex-item {
  display: flex;
  align-items: center !important;
}

button {
  /* 调整按钮的大小 */
  padding: 5px;
  /* 内边距 */
  font-size: 12px;
  /* 字体大小 */
}

.practiceType {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 120rpx;
}

.title {
  color: #333;
  font-size: 28rpx;
  font-weight: 500;
  // width: 300rpx;
  white-space: nowrap;
}

.title2 {
  color: #333;
  font-size: 28rpx;
  width: 120rpx;
}

.btnWarp {
  width: 140px;
  height: 49px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .u-button.data-v-2bf0e569 {
    height: 30px !important;
    margin-left: 10px;
  }

}

.title-warp {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 80rpx;
  background: #fff;

  .title {
    text-align: center;
    font-size: 28rpx;
    font-weight: 500;
    padding: 10rpx 24rpx;
    border-radius: 30rpx;
  }

  button {
    height: 30px !important;
    line-height: 30px !important;
    padding: 0 8px !important;
  }
}

.active {
  background: #4878FF;
  color: #fff;
}

.overFlow {
  width: 90%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.content-warp {
  color: #333;
  font-size: 24rpx;

  .item-warp {
    padding: 24rpx 24rpx 1rpx;
    width: 100%;
    // background: rgb(250, 242, 242);
    background: #fff;
    border-radius: 10px;
    margin-bottom: 30rpx;

    .requirement {
      width: 60%;
      // 溢出显示省略号
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }

    .btn {
      font-size: 26rpx;
      border: 1px solid #5ac725;
      padding: 5px 10px;
      border-radius: 20px;
      color: #5ac725;
      background: #fff;
    }

    .btnActive {
      border: 1px solid #5ac725;
      color: #5ac725;
    }
  }

  .txt-warp {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .title {
      display: inline-block;
      font-size: 30rpx;
      font-weight: bold;
      white-space: nowrap;
      // overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

.ellipsis-text {
  width: 95%;
  display: inline-block;
  align-items: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

::v-deep .uni-stat__select {
  // flex: 1;
  width: 80%;
  padding: 0 !important;

  view {
    width: 100%;
  }
}

.notYet {
  margin-top: 50rpx;
  width: 100%;
  text-align: center;
  font-weight: 0 !important;
  font-size: 42rpx;
}

.picker {
  padding: 10px;
  border: 1px solid #ccc;
  margin-bottom: 10px;
}

input {
  padding: 10px;
  border: 1px solid #ccc;
  width: 100%;
  line-height: 36px;
}
</style>
